<template>
  <view class="page">
	  <!-- 短租 / 长租 切换头部 -->
	  <view class="lease-tabs">
	    <view :class="['lease-tab', leaseType==='short'?'active':'']" @tap="switchLease('short')">短租</view>
	    <view :class="['lease-tab', leaseType==='long'?'active':'']" @tap="switchLease('long')">长租</view>
	  </view>
    <view class="tabs">
      <view :class="['tab-item', currentTab==='all'?'tab-item-active':'']" @tap="switchTab('all')">
        全部订单
        <!-- 全部订单：不显示角标 -->
      </view>
      <view :class="['tab-item', currentTab==='pending'?'tab-item-active':'']" @tap="switchTab('pending')">
        待支付
        <text class="badge" v-if="counts.pending>0">{{ displayCount(counts.pending) }}</text>
      </view>
      <view :class="['tab-item', currentTab==='doing'?'tab-item-active':'']" @tap="switchTab('doing')">
        进行中
        <text class="badge" v-if="counts.doing>0">{{ displayCount(counts.doing) }}</text>
      </view>
      <view :class="['tab-item', currentTab==='done'?'tab-item-active':'']" @tap="switchTab('done')">
        已完成
        <!-- 已完成：不显示角标 -->
      </view>
    </view>


    <!-- 空态（仅待支付且为空时显示） -->
    <view v-if="filteredOrders.length===0" class="empty-wrap">
      <image class="empty-img" mode="widthFix" src="https://kehu-1256834579.cos.ap-shanghai.myqcloud.com/weier/empty.png"></image>
      <text class="empty-text">暂无订单</text>
    </view>

    <!-- 列表 -->
    <view v-else-if="leaseType == 'short'" class="list">
      <view v-for="(item,idx) in filteredOrders" :key="idx" class="card">
        <view class="card-hd">
          <image class="logo" :src="logoUrl" mode="aspectFit"></image>
          <text class="title">{{ item.title }}</text>
          <text v-if="item.status==='pending'" class="status status-pending">待支付</text>
          <text v-else-if="item.status==='doing'" class="status status-doing">进行中</text>
          <text v-else-if="item.status==='done'" class="status status-done">已完成</text>
        </view>

        <view class="card-bd">
          <image class="thumb" :src="thumbUrl" mode="aspectFill"></image>
          <view class="meta">
            <view class="row"><text class="label">车辆编号：</text><text class="val">{{ item.code }}</text></view>
            <view class="row"><text class="label">使用时长：</text><text class="val">{{ item.duration }}</text></view>
            <view class="row"><text class="label">下单时间：</text><text class="val">{{ item.time }}</text></view>
          </view>
          <view class="price-box">
            <view class="price-row"><text class="price-gray">¥ {{ item.pay }}</text></view>
            <view class="price-row"><text class="price-gray">- ¥ {{ item.discount }}</text></view>
            <view class="price-final">¥{{ item.pay }}</view>
          </view>
        </view>

        <view class="card-ft">
          <view class="ft-left" @tap="onDelete(item)">删除</view>
          <view class="ft-right">
            <button v-if="item.status==='pending'" class="btn btn-primary" @tap="param_to_url('pay?rowid='+orders[idx].rowid+'&zfjl='+item.zfjl)">去支付</button>
            <button class="btn btn-plain" @tap="param_to_url('pay?act=details&rowid='+orders[idx].rowid+'&zfjl='+item.zfjl)">订单详情</button>
          </view>
        </view>
      </view>
    </view>
	<!-- 列表 -->
	<view v-else class="list">
	  <view v-for="(item,idx) in filteredOrders" :key="idx" class="card">
	    <view class="card-hd">
	      <image class="logo" :src="logoUrl" mode="aspectFit"></image>
	      <text class="title">{{ item.title }}</text>
	      <text v-if="item.status==='pending'" class="status status-pending">{{item.status_name}}</text>
	      <text v-else-if="item.status==='doing'" class="status status-doing">{{item.status_name}}</text>
	      <text v-else-if="item.status==='done'" class="status status-done">{{item.status_name}}</text>
	    </view>
	
	    <view class="card-bd">
	      <image class="thumb" :src="thumbUrl" mode="aspectFill"></image>
	      <view class="meta">
	       <view class="row">
	         <text class="tag-long">预约长租</text>
	       </view>
	        <view class="row"><text class="label">租赁时间：</text><text class="val">{{ item.time }}</text></view>
	        <view class="row"><text class="label">联系电话：</text><text class="val">{{ item.mobile }}</text></view>
	      </view>
	      <view class="price-box">
	        <view class="price-row"><text class="price-gray">{{ item.utime }}</text></view>
	        <view class="price-row"><text class="price-gray">- ¥ {{ item.discount }}</text></view>
	        <view class="price-final">¥{{ item.pay }}</view>
	      </view>
	    </view>
	
	    <view class="card-ft">
	      <view class="ft-left" @tap="onDelete(item)">删除</view>
	      <view class="ft-right">
			  <button v-if="data_list[idx].ddzt == '待支付押金'" class="btn btn-primary" @tap="to_pay_yajin(idx)">去支付押金</button>
	        <button v-else-if="item.status==='pending'" class="btn btn-primary" @tap="to_pay_changzu(idx)">支付租金</button>
	        <button class="btn btn-plain" @tap="param_to_url('changzu_order_details?rowid='+orders[idx].rowid)">订单详情</button>
			 <button class="btn btn-plain" @tap="param_to_url('huanche?rowid='+orders[idx].rowid)" v-if="item.status_name == '使用中'" style="background-color: #0496fc;color: #fff;">我要还车</button>
	      </view>
	    </view>
	  </view>
	</view>
  </view>
</template>

<script>
import common_config from '../../static/js/common.js';
var config = common_config.config;
var that;	
var userInfo;
export default {
  name: 'OrdersPage',
  data() {
    return {
	    leaseType: 'short', // 默认短租
      currentTab: 'all',
      logoUrl: 'https://kehu-1256834579.cos.ap-shanghai.myqcloud.com/weier/logo.png',
      thumbUrl: 'https://kehu-1256834579.cos.ap-shanghai.myqcloud.com/weier/che1.png',
      orders: [
       /* { title: 'Modrl F', code: '002', duration: '0小时30分钟', time: '2025.00.00 12:34', origin: 1000, discount: 912, pay: 88, status: 'pending' },
        { title: 'Modrl F', code: '001', duration: '1小时28分钟', time: '2025.00.00 00:00', origin: 1000, discount: 1000, pay: 88, status: 'doing' },
        { title: 'Modrl F', code: '001', duration: '1小时28分钟', time: '2025.00.00 00:00', origin: 1000, discount: 1000, pay: 88, status: 'done' },
        { title: 'Modrl F', code: '001', duration: '1小时28分钟', time: '2025.00.00 00:00', origin: 1000, discount: 1000, pay: 88, status: 'done' }*/
      ],
	  data_list:[]
    }
  },
  onLoad() {
  	that = this;
  	that.plusReady();
  },
  computed: {
    filteredOrders() {
      if (this.currentTab === 'all') return this.orders
      if (this.currentTab === 'pending') return this.orders.filter(o => o.status === 'pending')
      if (this.currentTab === 'doing') return this.orders.filter(o => o.status === 'doing')
      if (this.currentTab === 'done') return this.orders.filter(o => o.status === 'done')
      return this.orders
    },
    // 各状态数量（用于顶部红色角标）
    counts() {
      const c = { all: this.orders.length, pending: 0, doing: 0, done: 0 }
      this.orders.forEach(o => { if (o.status === 'pending') c.pending++; else if (o.status === 'doing') c.doing++; else if (o.status === 'done') c.done++; })
      return c
    }
  },
  methods: {
	  //初始化
	plusReady(){
	  	userInfo = uni.getStorageSync('userInfo');
	  	if(userInfo){
	  		userInfo = JSON.parse(userInfo);
	  		that.if_login = true;
			console.log(userInfo);
			that.load_datas();
	  	}else{
	  		that.if_login = false;
			uni.redirectTo({
				url:'/pages/index/login'
			});
	  	}
	  	
	},
	displayCount(n){ return n>99 ? '99+' : n },
	load_datas(){
		uni.request({
		  url: config.request_url+'/v2/open/worksheet/getFilterRows',
		  method: 'POST',
		  header: {
			'Content-Type': 'application/json'
		  },
		  data: {
			"appKey": config.appKey,
			"sign": config.sign,
			"worksheetId": that.leaseType == 'short' ? "ddgl" : "czddgl",
			"pageSize": 50,
			"pageIndex": 1,
			"filters": [
				{
					"controlId": "yonghu",
					"dataType": 29,
					"spliceType": 1,
					"filterType": 24,
					"value": userInfo.rowid//用户记录的rowid
				}
			]
		  },
		  success: (res) => {
			console.log('返回结果:', res.data);
			res = res.data;
			console.log(res);
			if(res.success){
				var arr = [];
				var datas = res.data.rows;
				that.data_list = datas;
				if(that.leaseType == 'short'){
					for(var i = 0;i < datas.length;i++){
						var status = '';
						var price = '0.00';
						var duration = '0小时0分钟';
						if(datas[i].ddzt == '使用中'){
							status = 'doing';
						}
						if(datas[i].ddzt == '支付成功'){
							status = 'done';
						}
						if(datas[i].ddzt == '待支付'){
							status = 'pending';
						}
						var r = JSON.parse(datas[i].zfjl);
						
						arr.push({
							title: datas[i].sbflmc, code: datas[i].ddbh, duration: duration, time: datas[i].ctime, origin: price, discount: 0, pay: datas[i].jine, status: status,rowid:datas[i].rowid,zfjl:r[0]
						});
					}
				}else{
					var status = '';
					for(var i = 0;i < datas.length;i++){

						if(datas[i].ddzt == '已完成'){
							status = 'done';
						}
						if(datas[i].ddzt == '支付成功' || datas[i].ddzt == '使用中' || datas[i].ddzt == '归还中' || datas[i].ddzt == '协商理赔'){
							status = 'doing';
						}
						if(datas[i].ddzt == '待支付押金' || datas[i].ddzt == '待支付租金'){
							status = 'pending';
						}
						//var r = JSON.parse();
						console.log(datas[i].zfjl);
						var r = JSON.parse(datas[i].zfjl);
						arr.push({
							title: 'Modrl F', code: datas[i].ddbh, mobile: datas[i].shrlxdh, time: datas[i].utime, origin: price, discount: 0, pay: datas[i].jine,yajin:datas[i].yjje, status: status,rowid:datas[i].rowid,status_name:datas[i].ddzt,zfjl:datas[i].zfjl
						});
					}
					//console.log(datas[i].ddbh);
					/*arr.push({
						title: 'Modrl F', code: datas[i].ddbh, duration: duration, time: datas[i].ctime, origin: price, discount: 0, pay: datas[i].jine, status: status,rowid:datas[i].rowid
					});*/
				}
				
				console.log(arr);
				if(arr.length > 0){
					that.orders = arr;
				}
			}else{
				 uni.showToast({ title: res.data.msg || '数据获取失败', icon: 'none' });
			}
		  },
		  fail: (err) => {
			console.error('请求失败:', err);
			uni.showToast({ title: '网络错误', icon: 'none' });
		  }
		})  
	},
	to_pay_changzu(index){
		
		uni.navigateTo({
			url:'/pages/index/yuyue_to_pay?czddRowid='+that.data_list[index].rowid+'&yajinRowid='+that.data_list[index].yajinRowid+'&zujinRowid='+that.data_list[index].zujinRowid+'&rowid='+that.data_list[index].rowid
		})
	},
	to_pay_yajin(index){
		console.log(that.data_list[index].ddzt);
		uni.navigateTo({
			url:'/pages/index/yajin?czddRowid='+that.data_list[index].rowid+'&yajinRowid='+that.data_list[index].yajinRowid+'&zujinRowid='+that.data_list[index].zujinRowid+'&rowid='+that.data_list[index].rowid+'&money='+that.data_list[index].yjje
		});
	},
	switchLease(type) {
		if(this.leaseType == type){
			return false;
		}
		that.orders = [];
	      this.leaseType = type
	  // 如果需要切换时重新请求数据，可以这里调用 load_datas()
	   this.load_datas()
	},
    switchTab(key) { this.currentTab = key },
    param_to_url(url){ uni.navigateTo({ url }) },
    onPay(item) { uni.showToast({ title: '去支付', icon: 'none' }) },
    onDetail(item) { uni.showToast({ title: '查看订单详情', icon: 'none' }) },
    onDelete(item) {
      uni.showModal({
        title: '提示',
        content: '确认删除该订单吗？',
        success: (res) => { if (res.confirm) { this.orders = this.orders.filter(o => o !== item) } }
      })
    },
    // 如果你要在运行时再加一条“待支付”订单，可调用这个方法：
    addPendingDemo() {
      this.orders.unshift({ title: 'Modrl F', code: '003', duration: '0小时15分钟', time: '2025.00.00 18:00', origin: 1000, discount: 900, pay: 100, status: 'pending' })
    }
  }
}
</script>

<style scoped>
.page { padding: 0rpx; background-color: #f7f8fa; min-height: 100vh; }
.tabs { display: flex; align-items: center; justify-content: space-around; background-color: #ffffff; height: 88rpx; border-bottom: 1rpx solid #f0f0f0; }
.tab-item { font-size: 28rpx; color: #666666; padding: 0 12rpx; height: 88rpx; line-height: 88rpx; position: relative; display: flex; align-items: center; gap: 8rpx; }
.tab-item-active { color: #333333; font-weight: 600; }
.tab-item-active::after { content: ''; position: absolute; left: 50%; transform: translateX(-50%); bottom: 0rpx; width: 60rpx; height: 6rpx; border-radius: 6rpx; background-color: #1a73e8; }
.badge { width: 28rpx; height: 28rpx; border-radius: 50%; background-color: #dd2727; color: #fff; font-size: 20rpx; display: inline-flex; align-items: center; justify-content: center; line-height: 28rpx; padding: 0; transform: translateY(-2rpx); }
.empty-wrap { padding-top: 120rpx; display: flex; flex-direction: column; align-items: center; }
.empty-img { width: 460rpx; }
.empty-text { margin-top: 16rpx; font-size: 26rpx; color: #999999; }
.list { padding: 24rpx; }
.card { background-color: #ffffff; border-radius: 16rpx; padding: 20rpx 20rpx 8rpx 20rpx; box-shadow: 0 4rpx 16rpx rgba(0,0,0,0.04); margin-bottom: 20rpx; }
.card-hd { display: flex; align-items: center; justify-content: flex-start; }
.logo { width: 40rpx; height: 40rpx; border-radius: 20rpx; margin-right: 12rpx; }
.title { font-size: 30rpx; color: #222222; font-weight: 600; }
.status { margin-left: auto; font-size: 26rpx; }
.status-pending { color: #ff4d4f; }
.status-doing { color: #1a73e8; }
.status-done { color: #999999; }
.card-bd { display: flex; align-items: stretch; margin-top: 18rpx; }
.thumb { width: 152rpx; height: 152rpx; border-radius: 12rpx; background-color: #f2f3f5; overflow: hidden; margin-right: 16rpx; }
.meta { flex: 1; }
.row {
  display: flex;
  align-items: center;
  justify-content: flex-start;
  height: 44rpx;
  line-height: 44rpx;
}
/* 左边固定宽度，不换行 */
.label {
  flex: 0 0 120rpx;     /* 这里宽度你可以按字数调，比如 150~180rpx */
  font-size: 26rpx;
  color: #666;
  text-align: left;     /* 这里用左对齐，跟你截图里一致 */
  white-space: nowrap;
}

/* 右边占满剩余空间，不换行，超出可省略 */
.val {
  flex: 1;
  min-width: 0;
  font-size: 26rpx;
  color: #333;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
}
.price-box { width: 160rpx; display: flex; flex-direction: column; align-items: flex-end; justify-content: center; }
.price-row { line-height: 36rpx; }
.price-gray { color: #b0b0b0; font-size: 24rpx;}
.price-final { color: #222222; font-size: 34rpx; font-weight: 700; margin-top: 6rpx; }
.card-ft { padding-top: 16rpx; display: flex; align-items: center; justify-content: space-between; }
.ft-left { font-size: 24rpx; color: #999999; }
.ft-right { display: flex; align-items: center; }
.btn { height: 60rpx; line-height: 60rpx; padding: 0 24rpx; font-size: 26rpx; border-radius: 30rpx; margin-left: 12rpx; background-color: #f5f5f5; color: #333333; border: none; }
.btn-primary { background-color: #ff4d4f; color: #ffffff; }
.btn-plain { background-color: #ffffff; color: #666666; border: 1rpx solid #e5e5e5; }
.lease-tabs {
  display: flex;
  background-color: #f2f2f2;
  border-radius: 40rpx;
  margin: 20rpx auto;
  width: 300rpx;
  height: 60rpx;
  overflow: hidden;
}
.lease-tab {
  flex: 1;
  text-align: center;
  line-height: 60rpx;
  font-size: 28rpx;
  color: #666;
}
.lease-tab.active {
  background-color: #1a73e8;
  color: #fff;
  font-weight: 600;
}
.tag-long {
  background-color: #1a73e8;  /* 蓝底 */
  color: #fff;                /* 白字 */
  font-size: 24rpx;           /* 字号稍微小点 */
  padding: 6rpx 16rpx;        /* 内边距 */
  border-radius: 30rpx;       /* 圆角 */
  line-height: 32rpx;
}
</style>
